﻿using System;
using System.Windows.Forms;
using org.se.fs.presenter.Library;
using org.se.fs.presenter.View;

namespace org.se.fs.view
{
    public partial class FrmLogin : Form, presenter.IView.ILogin
    {
        #region Public Property Variable
        public string Username
        {
            get { return txtUsername.Text; }
            set { txtUsername.Text = value; }
        }
        public string Userpass
        {
            get { return txtPassword.Text; }
            set { txtPassword.Text = value; }
        }
        public void ButtonLoginEnable(bool enable)
        {
            btnLogin.Enabled = enable;
        }
        public void FocusUsername()
        {
            txtUsername.Focus();
        }
        public void FocusUserpass()
        {
            txtPassword.Focus();
        }
        #endregion

        private readonly Login _presenter;

        public FrmLogin()
        {
            InitializeComponent();
            _presenter = new Login(this);
            _presenter.OnAuthenticate += PresenterOnAuthenticate;
            _presenter.Initialize();
        }

        void PresenterOnAuthenticate(object source, FormEvent e)
        {
            if(!e.IsSuccess)
            {
                MessageBox.Show(e.Exception.Message, @"Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUsername.Focus();
                return;
            }

            txtPassword.Text = string.Empty;
            Visible = false;
            var frmForm = new FrmMain();
            frmForm.FormClosed += FrmFormFormClosed;
            frmForm.Show();
        }

        void FrmFormFormClosed(object sender, FormClosedEventArgs e)
        {
            Visible = true;
        }

        private void BtnCloseClick(object sender, EventArgs e)
        {
            Close();
        }

        private void BtnLoginClick(object sender, EventArgs e)
        {
             _presenter.Authenticate();
        }

        private void Button1Click(object sender, EventArgs e)
        {
            txtUsername.Text = @"Admin";
            txtPassword.Text = @"Admin";
            btnLogin.PerformClick();
        }
    }
}
